<!-- 使用 type="home" 属性设置首页，其他页面不需要设置，默认为page；推荐使用json5，更强大，且允许注释 -->
<route lang="json5" type="home">
{
  style: {
    navigationStyle: 'default',
    navigationBarTitleText: '首页',
    navigationBarBackgroundColor: '#FFFFFF',
  },
}
</route>
<template>
  <navbar leftIcon="" text="心康医疗" />
  <view class="scroll">
    <view
      class="home public-page"
      :style="{ height: `calc(100vh - ${safeAreaInsets?.top}px - 44px - 54px)` }"
    >
      <view class="public-background">
        <scroll @scrollChange="scrollChange" :time="2000">
          <!-- 产品 -->
          <view class="public-height"></view>
          <view class="swiper-box">
            <uv-swiper
              bgColor="#ffffff"
              :list="homeList()"
              :indicator="false"
              radius="20rpx"
              keyName="homeUrl"
              height="390rpx"
              imgMode="aspectFill"
              :circular="false"
              :autoplay="false"
              @click="jumpAdvertisement"
            ></uv-swiper>
          </view>

          <!-- 设备 -->
          <view class="device-box">
            <deviceReport
              ref="deviceRef"
              v-model:status="DPParams.status"
              v-model:sn="DPParams.sn"
              v-model:name="DPParams.name"
              v-model:model="DPParams.model"
            />
          </view>

          <!-- 心率图 -->
          <view class="ecg-box">
            <heartRate :params="lineParams" @gainChange="gainChange" @speedChange="speedChange" />
            <view class="ecg-bg">
              <view class="ecg-content">
                <canvas class="canvas-bg" type="2d"></canvas>
                <canvas class="canvas-font" type="2d"></canvas>

                <view class="canvas-line-box">
                  <view
                    class="line-left"
                    :style="{
                      minWidth: lineParams.ppm * 5 + 'px',
                    }"
                  ></view>
                  <view class="line-box">
                    <canvas class="canvas-timer" type="2d"></canvas>
                    <view class="line-more">
                      <canvas
                        class="canvas-line"
                        type="2d"
                        :style="{
                          width: lineParams.canvasWidth ? `${lineParams.canvasWidth}px` : '100%',
                          height: lineParams.canvasHeight ? `${lineParams.canvasHeight}px` : '100%',
                        }"
                      ></canvas>
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </view>
          <view style="width: 100%; height: 44px"></view>
        </scroll>
      </view>
    </view>
    <uv-picker
      ref="gainRef"
      title="选择增益"
      round="10"
      keyName="name"
      :defaultIndex="[gainDefaultIndex]"
      :columns="[gainGroup]"
      confirmColor="#e50038"
      @confirm="gainConfirm"
    ></uv-picker>
    <uv-picker
      ref="speedRef"
      title="选择走速"
      round="10"
      keyName="name"
      :defaultIndex="[speedDefaultIndex]"
      :columns="[speedGroup]"
      confirmColor="#e50038"
      @confirm="speedConfirm"
    ></uv-picker>
  </view>
  <tabBar :current="0" />
</template>

<script lang="js" setup>
import navbar from '@/components/navbar'
import deviceReport from '@/pages/deviceReport'
import heartRate from '@/pages/heartRate'
import tabBar from '@/custom-tab-bar'
import swiper from './method/swiper'
import useEcgCall from './method/useEcgCall'
import useScan from './method/useScan'
// import jsonData from '@/json/jsonData.json'
import { getElement } from './method/ecgPublic'
import scroll from '@/components/scrollView'
import {
  initEcgPart,
  initEcgParams,
  initComputedParams,
  pushData,
  loop,
  clearCanvas,
  clearQueueLoopTimer,
} from './method/activeEcgLine'
import { isLoginEd, getSn, getClientTime } from '@/utils/publicMethods'
import { gainGroup, speedGroup } from '@/utils/params'
const { safeAreaInsets } = uni.getWindowInfo()
// --------------------------轮播图------------------------------
const { homeList, jumpAdvertisement } = swiper()

// -------------------------波形图参数、方法-----------------------------
const { getLineWidth, drawBg_, drawFont_, drawLine_, drawTimer_ } = useEcgCall()
// 基础参数
const lineParams = reactive({
  leadValueList: [1], //一组导联需要画线的下标值，只画一条线，且是第二条线
  leadNameList: ['I', 'II'],
  lineData: [[0]],
  ecgBeat: [],
  nFs: parseFloat('250'),
  duvp: parseFloat('2.44'),
  canvasWidth: 0,
  canvasHeight: 0,
  ppm: 4,
  gain: 10,
  speed: 25,
  lineWidth: 1.5,
  isDrawRR: false,
  baseLineValue: 4 * 4,
  element: '.canvas-line',
  leadCount: 12,
})

// 获取canvas宽度
const getCanvasCSS = async (initData) => {
  const lineBox = await getElement('.line-box')
  lineParams.canvasHeight = lineBox?.height ? Math.floor(lineBox?.height) : 0
  if (initData) {
    lineParams.canvasWidth = lineBox?.width ? Math.floor(lineBox?.width) : 0
  } else {
    lineParams.canvasWidth = getLineWidth(lineParams) ? Math.floor(lineParams) : 0
  }
}

// 打开走速
const speedDefaultIndex = ref(0)
const speedRef = ref(null)
const speedChange = (data) => {
  speedDefaultIndex.value = speedGroup.findIndex((o) => o.id === lineParams.speed)
  speedRef.value.open()
}

// 打开增益
const gainDefaultIndex = ref(0)
const gainRef = ref(null)
const gainChange = (data) => {
  gainDefaultIndex.value = gainGroup.findIndex((o) => o.id === lineParams.gain)
  gainRef.value.open()
}

// 增益选择
const gainConfirm = (val) => {
  lineParams.gain = val.value[0].id
  // 重画标志
  drawFont_(lineParams)
  // 重画时间
  drawTimer_(lineParams)
  // 重画波形
  initEcgLine()
}

// 走速选择
const speedConfirm = (val) => {
  lineParams.speed = val.value[0].id
  // 重画标志
  drawFont_(lineParams)
  // 重画时间
  drawTimer_(lineParams)
  // 重画波形
  initEcgLine()
}

// ---------------canvas方法、工厂调用-----------------

onShow(async () => {
  if (!isLoginEd()) {
    console.log('未登录，停止绘制波形')
    await clearQueueLoopTimer()
    await clearCanvas()
    return
  }
})
onBeforeMount(async () => {
  await initEcgBgFont()
  initEcgLine()
})

let isDrawCanvas = false
// 初始化波形图标志位和标志位
const initEcgBgFont = async () => {
  isDrawCanvas = false
  /* 1、获取初始化宽度 */
  await getCanvasCSS(true) //波形线的宽度
  /* 2、画标志位和背景 */
  await drawBg_(lineParams)
  await drawFont_(lineParams)
  await drawTimer_(lineParams)
  /* 3、画初始化直线 */
  // lineParams.lineData = JSON.parse(JSON.stringify(jsonData.AveEcgData))
  // lineParams.nFs = parseFloat(jsonData.SampleRate)
  // lineParams.duvp = parseFloat(jsonData.ADResolution)
  // await drawLine_(lineParams)
  isDrawCanvas = true
}

const initEcgLine = async () => {
  // 初始化动态波形参数
  const isGetContext = await initEcgParams(lineParams)
  if (!isGetContext) {
    console.log('获取不到canvas对象，请检查canvas是否渲染完成')
    return
  }
  // 初始化计算参数
  initComputedParams({})
  // 清除画布内容
  clearCanvas()
  // 开启画图定时
  loop()
}

// ---------------------定时接收数据------------------------
onUnload(() => {
  uni.$off('subscription')
  uni.$off('weChartInit')
  uni.$off('stopEcgInit')
})
onLoad(() => {
  // let i = 0
  // setInterval(() => {
  //   i++
  //   // if (i > 10) {
  //   //   clearInterval()
  //   //   return
  //   // }
  //   lineParams.lineData = JSON.parse(JSON.stringify(jsonData.EcgData))
  //   lineParams.nFs = parseFloat(jsonData.SampleRate)
  //   lineParams.duvp = parseFloat(jsonData.ADResolution)
  //   initEcgPart(lineParams)
  //   pushData(lineParams.lineData)
  // }, 5000)

  // 接收hub数据
  let onShowTimer = null
  uni.$on('weChartInit', async (option) => {
    await clearQueueLoopTimer()
    await clearCanvas()
    if (option === 'onShow') {
      onShowTimer = new Date().getTime()
      console.log('切回前台时间：', new Date(onShowTimer).toISOString().slice(11, 19))
      loop()
    }
  })

  uni.$on('stopEcgInit', async (option) => {
    clearQueueLoopTimer()
    initComputedParams({}, true)
    console.log(option)
  })

  uni.$on('subscription', async (option) => {
    let status = true
    if (option.topic.includes('/hub/status_reply')) {
      status = option.message?.active
      if (!status) return
    }

    if (option.topic.includes('/status_reply')) {
      status = option.message?.connected
      if (!status) return
    }

    if (option.topic.includes('realtime_data') && status) {
      const timestamp = option.message.timestamp
      if (onShowTimer && onShowTimer > timestamp) {
        return
      }

      if (timestamp < getClientTime()) {
        return
      }

      if (!isLoginEd()) {
        await clearQueueLoopTimer()
        await clearCanvas()
        console.log('未登录，停止绘制波形')
        return
      }

      // 是否和当前用户的sn号一致
      const sn = getSn()
      const parts = option.topic.split('/')[2]
      if (sn !== parts) {
        await clearQueueLoopTimer()
        await clearCanvas()
        console.log('非当前用户设备，无需订阅消息-ecg！: ', sn, parts)
        return
      }

      const otherData = JSON.parse(option.message.json)
      const waveData = option.message?.waveData || []
      if (!waveData.length) return
      console.log(
        `${onShowTimer && new Date(onShowTimer).toISOString().slice(11, 19)}<${timestamp && new Date(timestamp).toISOString().slice(11, 19)}`,
        waveData.length,
      )
      onShowTimer = null

      lineParams.nFs = parseFloat(otherData.SampleRate)
      lineParams.duvp = parseFloat(otherData.ADResolution)
      lineParams.lineData = waveData
      initEcgPart(lineParams)
      pushData(lineParams.lineData)
    }
  })
})

// -------------------------下拉加载-----------------------------
const deviceRef = ref(null)
const scrollChange = () => {
  // 初次加载画波形图背景和标志位
  if (!isDrawCanvas) initEcgBgFont()
  deviceRef.value.deviceScroll()
}

// -----------------------扫描外面普通二维码-------------------------------
const { isOptionP } = useScan()
onLoad((option) => {
  // 设备绑定跳转的
  const params = isOptionP(option)
  if (option?.sn && option?.type === 'device') {
    getPageInfo(option)
    // 扫码进来的
  } else if (params?.sn && option?.type === 'scan') {
    getPageInfo(option)
  }
})
// 二维码解析参数调用
const DPParams = ref({ sn: '', model: '', name: '' })
const getPageInfo = async (option) => {
  DPParams.value.sn = option.sn
  DPParams.value.name = option.name
  DPParams.value.model = option.model
}

// -------------------微信分享----------------------
// 分享至好友/群聊
onShareAppMessage((res) => {
  return {
    title: '首页',
    path: getCurrentPages()[0].$page.fullPath,
    success: (res) => {},
    fail: (res) => {},
  }
})
// 分享到朋友圈
onShareTimeline((res) => {
  return {
    title: '首页',
    path: getCurrentPages()[0].$page.fullPath,
    success: (res) => {},
    fail: (res) => {},
  }
})
</script>
<style lang="scss" scoped>
@import './style/ecg';
.home {
  .swiper-box {
    height: 390rpx;
    background: #ffffff;
    border-radius: 20rpx;
  }
  .device-box {
    min-height: 500rpx;
    margin-top: 30rpx;
    background: #ffffff;
    border-radius: 20rpx;
  }
  .ecg-box {
    margin-top: 30rpx;
    background: #ffffff;
    border-radius: 20rpx;
  }
}
</style>
